<template>
  <ContentWrap>
    <!--    顶部查询项-->
    <el-form :model="form" inline label-width="100px">
      <el-form-item :label="t('product.cname')">
        <el-input
          v-model="form.cname"
          clearable
          :placeholder="'请输入' + t('product.cname')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('product.abbr')">
        <el-input
          v-model="form.abbr"
          clearable
          :placeholder="'请输入' + t('product.abbr')"
          style="width: 250px"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="initialize">查询</el-button>
        <el-button icon="Refresh" @click="reset">重置</el-button>
        <BaseButton type="success" @click="handleExport">商品导出</BaseButton>
      </el-form-item>
    </el-form>
    <!-- 表格主体 -->
    <el-table
      :data="dataList"
      highlight-current-row
      stripe
      border
      v-loading="tableLoading"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center' }"
    >
      <el-table-column :label="t('product.id')" prop="id" width="80" />
      <el-table-column
        :label="t('product.cname')"
        prop="cname"
        :show-overflow-tooltip="true"
        min-width="200"
      />
      <el-table-column
        :label="t('product.abbr')"
        prop="abbr"
        width="200"
        :show-overflow-tooltip="true"
      />

      <el-table-column :label="t('product.hashrate')" prop="hashrate" :show-overflow-tooltip="true">
        <template #default="{ row }">
          {{
            row.hashrate
              ? row.hashrate + useEnumeratePicker(comput_unitList, row.computing_unit)
              : ''
          }}
        </template>
      </el-table-column>

      <el-table-column :label="t('product.power')" prop="power" :show-overflow-tooltip="true">
        <template #default="{ row }">
          {{ row.power ? row.power + 'W' : '' }}
        </template>
      </el-table-column>

      <el-table-column
        :label="t('product.remark')"
        prop="remark"
        min-width="360"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          <div
            v-if="editingRowId !== row.id"
            class="remark-readonly"
            @click="handleEditRemark(row)"
            :title="row.remark"
            :style="{
              cursor: 'pointer',
              color: row.remark ? '#606266' : '#409eff'
            }"
          >
            {{ row.remark || '点击设置' }}
          </div>
          <el-input
            v-else
            v-model="editingRemark"
            @blur="handleSaveRemark(row)"
            @keyup.enter.stop="handleSaveRemark(row)"
            @keyup.esc.stop="handleCancelEdit"
            placeholder="请输入备注内容"
            :ref="(el) => setRemarkInputRef(el)"
            :disabled="remarkSaving"
            autofocus
          >
            <template #suffix>
              <el-icon v-if="remarkSaving" class="is-loading">
                <Loading />
              </el-icon>
            </template>
          </el-input>
        </template>
      </el-table-column>
    </el-table>

    <!--    分页-->
    <Pagination
      :total="paginationTotal"
      v-model:page="form.pageIndex"
      v-model:limit="form.pageSize"
      @pagination="initialize"
    />
  </ContentWrap>
</template>

<script setup lang="ts">
import Pagination from '@/components/Pagination/index.vue'
import { ContentWrap } from '@/components/ContentWrap'
import { useEnumeratePicker, calculateColumnWidth } from '@/utils'
import { getListApi, saveDataApi } from '@/api/product'
import { getGoodsEnumApi } from '@/api/product'
import { exportProductApi } from '@/api/product'
import dayjs from 'dayjs'
const { t } = useI18n()
const { push } = useRouter()

const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const paginationTotal = ref<number>(0)

// 编辑状态管理
const editingRowId = ref<number | null>(null)
const editingRemark = ref<string>('')
const remarkInputRef = ref<any>(null)
const remarkSaving = ref<boolean>(false)

const form = ref<Record<string, any>>({
  cname: '',
  abbr: '',
  pageIndex: 1,
  pageSize: 30
})

const comput_unitList = ref<Array<Record<string, any>>>([])

//设置输入框引用
const setRemarkInputRef = (el: any) => {
  remarkInputRef.value = el
}

//处理备注编辑
const handleEditRemark = (row: Record<string, any>) => {
  editingRowId.value = row.id
  editingRemark.value = row.remark || ''
  // 使用 nextTick 确保输入框渲染完成后再聚焦
  nextTick(() => {
    if (remarkInputRef.value) {
      remarkInputRef.value.focus()
    }
  })
}

//保存备注编辑
const handleSaveRemark = async (row: Record<string, any>) => {
  if (!editingRemark.value) {
    return
  }
  if (editingRemark.value !== row.remark) {
    remarkSaving.value = true
    try {
      const resp = await saveDataApi({ id: row.id, remark: editingRemark.value.trim() })
      if (resp.code === 0) {
        initialize()
        ElMessage.success(t('common.operateSucMsg'))
      } else {
        ElMessage.error(t('common.operateFailMsg'))
      }
    } finally {
      remarkSaving.value = false
    }
  }
  // 退出编辑状态
  editingRowId.value = null
  editingRemark.value = ''
}

//取消编辑
const handleCancelEdit = () => {
  editingRowId.value = null
  editingRemark.value = ''
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getGoodsEnumApi({ field: 'all' })
  comput_unitList.value = resp.data.comput_unit
}
const handleExport = () => {
  nextTick(async () => {
    await exportProductApi({}, `商品管理_${dayjs().format('YYYY.MM.DD')}.xlsx`)
  })
}
//初始化请求
const initialize = async () => {
  tableLoading.value = true
  const params = JSON.parse(JSON.stringify(form.value))

  const resp = await getListApi(params)
  dataList.value = resp.data.list

  paginationTotal.value = resp.data.total
  tableLoading.value = false
}

//重置查询项
const reset = () => {
  form.value = {
    cname: '',
    abbr: '',
    pageIndex: 1,
    pageSize: 30
  }
  paginationTotal.value = 0
  initialize()
}

onMounted(() => {
  getDropDownBoxInfo()
  initialize()
})
</script>

<style lang="less" scoped>
:deep(.el-table--default .el-table__cell) {
  padding: 2px 0 !important;
}

:deep(.el-table--default .cell) {
  padding: 0 4px;
}

/* 备注只读状态样式 */
.remark-readonly {
  display: flex;
  min-height: 24px;
  padding: 4px 8px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.2s ease;
  align-items: center;
  justify-content: center;
}

.remark-readonly:hover {
  background-color: #f5f7fa;
  border: 1px dashed #409eff;
}
</style>
